package com.jlnk.gsondemo.views;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.jlnk.gsondemo.R;
import com.jlnk.gsondemo.adapter.HotSearchAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BaiduHotSearchActivity extends AppCompatActivity {
    private RecyclerView hotSearchRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baidu_hot_search);

        hotSearchRecyclerView = findViewById(R.id.hot_search_recycler_view);

        String jsonStr = getJson("hotsearch.json");
        displayHotSearchList(jsonStr);
    }

    private String getJson(String fileName) {
        StringBuilder json = new StringBuilder();
        try {
            InputStream is = getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    private void displayHotSearchList(String jsonData) {
        try {
            JSONArray hotSearchList = new JSONObject(jsonData).getJSONArray("result");

            HotSearchAdapter adapter = new HotSearchAdapter(hotSearchList);
            hotSearchRecyclerView.setAdapter(adapter);
            hotSearchRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}